package com.mangatta.ec2.activity;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.widget.Toast;
import com.mangatta.cloud.dao.InstanceDetailDao;
import com.mangatta.cloud.ec2.Ec2Instance;
import com.mangatta.ec2.monitor.InstanceListMonitor;
import com.mangatta.ec2.util.Util;

import java.util.List;

public class AuthPrefActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
    private static final String TAG = AuthPrefActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.auth_pref);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (Util.isAwsCredentialKey(key) && Util.isAWSCredentialsAvailable(this)) {
            new Ec2InstanceLoader().execute();
        }
    }

    private class Ec2InstanceLoader extends AsyncTask<String, Integer, String> {
        private List<Ec2Instance> ec2Instances = null;
        private boolean isError = false;

        @Override
        protected String doInBackground(String... strings) {
            try {
                InstanceListMonitor instanceListMonitor = new InstanceListMonitor(
                        Util.getAWSCredentails(AuthPrefActivity.this));
                this.ec2Instances = instanceListMonitor.getInstancesDetail();

                // Persist in DB
                InstanceDetailDao instanceDetail = new InstanceDetailDao(AuthPrefActivity.this);
                instanceDetail.persistInstanceDetail(ec2Instances);

                return "Successfully fetched details on instances";
            } catch (Exception e) {
                isError = true;
                Log.e(TAG, "Exception occurred when trying to get instances.", e);
                return "Failed to fetch instances";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            String message = null;
            if (isError) {
                message = "Instance fetch failed for the specified preference";
            } else if (ec2Instances == null || ec2Instances.size() == 0) {
                message = "No instances found in the given account";
            } else {
                message = String.format("Identified %d instance(s)", ec2Instances.size());
            }
            Toast.makeText(AuthPrefActivity.this, message, Toast.LENGTH_LONG).show();
        }
    }
}
